﻿using Project_veilingsite.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web;
using System.Web.Helpers;
using System.Web.Mvc;

namespace Project_veilingsite.Controllers
{
    public class ContactController : Controller
    {
        //Opvragen pagina
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        //E-mail versturen
        [HttpPost]
        public ActionResult Index(ContactModel model)
        {
            try
            {
                var fromAddress = new MailAddress("aspproject.3aon@gmail.com", "PROJECT ASP");
                var toAddress = new MailAddress("aspproject.3aon@gmail.com", "Steven Verheyen"); //Voor testings naar dit e-mailadres
                const string fromPassword = "aspwachtwoord1";
                string subject = "Project ASP - " + model.Title;
                string body = model.Message + " (e-mail: " + model.Email + ")";

                var smtp = new SmtpClient
                {
                    Host = "smtp.gmail.com",
                    Port = 587,
                    EnableSsl = true,
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    UseDefaultCredentials = false,
                    Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
                };

                using(var message = new MailMessage(fromAddress, toAddress)
                                    {
                                        Subject = subject,
                                        Body = body
                                    })
                {
                    smtp.Send(message);
                }

                return RedirectToAction("Feedback");
            }
            catch (Exception e)
            {
                //Server.MapPath("~") = de root-map van het project
                string pad = Server.MapPath("~") + "/LoggingTracing/tracingLogging.txt";
                if (!System.IO.File.Exists(pad))
                {
                    System.IO.File.Create(pad);
                }

                using (StreamWriter swTracing = System.IO.File.AppendText(pad))
                {
                    swTracing.Write("\n\nDatum/Tijd: " + DateTime.Now + "\nException: " + e.StackTrace);
                }
            }

            return View();
        }

        public ActionResult Feedback()
        {
            ViewData["titel"] = "E-mail Verstuurd";
            ViewData["h2"] = "E-mail met succes verstuurd";
            ViewData["boodschap"] = "Er is een e-mail verstuurd naar de site administrator. Hij zal, indien nodig, spoedig contact met u opnemen";

            return View();
        }
    }
}